package com.itboye.eweilisten.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.itboye.eweilisten.R;
import com.itboye.eweilisten.adapter.HomeAdapter;
import com.itboye.eweilisten.app.MyApplication;
import com.itboye.eweilisten.base.BaseFragment;
import com.itboye.eweilisten.me.home.ActivityGoodsTetail;
import com.itboye.eweilisten.me.login.LoginActivity;
import com.itboye.eweilisten.me.personal.activity.WebActivity;
import com.itboye.eweilisten.model.Homebean;
import com.itboye.eweilisten.model.UpdateVersionBean;
import com.itboye.eweilisten.presenter.UpdatePresenter;
import com.itboye.eweilisten.presenter.UserPresenter;
import com.itboye.eweilisten.util.loadingutil.MAlert;
import com.itboye.eweilisten.util.sputil.Const;
import com.itboye.eweilisten.util.update.UpdateManager;
import com.itboye.eweilisten.util.widget.CarouselView;
import com.itboye.eweilisten.util.widget.IsStringSPUtils;
import com.itboye.eweilisten.util.widget.MyListView;
import com.itboye.eweilisten.util.widget.XImageLoader;
import com.itboye.eweilisten.util.widget.XScrollView;
import com.itboye.eweilisten.volley.ResultEntity;

import java.util.Observable;
import java.util.Observer;

/**
 * 首页
 */
public class HomeFragment extends BaseFragment implements Observer{
    private ListView myListView;
    HomeAdapter adapter;
    private UserPresenter presenter;
    CarouselView cCarouselView;
    private TextView mTextview, tvweiceshi;
    private ImageView imgHemo;
    private XScrollView xscrollview;
    private LinearLayout linHome;
    Homebean homebean = new Homebean();
    private SwipeRefreshLayout mSwipeLayout;
    TextView tvGongao;
    RelativeLayout relyoutGongao, linteMessge;
    private String id;
    UpdatePresenter updatePresenter;
    @Override
    public int initView() {
        return R.layout.fragment_home;

    }

    @Override
    public void onMyActivityCreated() {

        init();
    }

    private void init() {
        IntentFilter connect_recover = new IntentFilter("connect_recover");
        getActivity().registerReceiver(netBroadcastReceiver,connect_recover);
        presenter = new UserPresenter(this);
        presenter.onHomeLunbo("20", IsStringSPUtils.IsUid(),IsStringSPUtils.getSid());
        tvGongao.setText("公告");
        showProgressDialog("数据加载中...", true);
        linHome.setBackgroundResource(R.color.white);
        imgHemo = (ImageView) getActivity().findViewById(R.id.imgHemo);

        //   imgHemo.setVisibility(View.VISIBLE);
        //   cCarouselView.setVisibility(View.GONE);
        myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), ActivityGoodsTetail.class);
                intent.putExtra("id", homebean.getBook().get(position).getP_id());
                Log.d("homebean", homebean.getBook().get(position).getP_id());
                startActivity(intent);
            }
        });
        MyListView.LayoutParams params = new ListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        //   cCarouselView.setLayoutParams(params);
        myListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {

            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {
                changeTitle(getScroll());
            }
        });
        //获取焦点。，去掉后每次页面返回，MyGridView会在上面
        imgHemo.setFocusable(true);
        imgHemo.setFocusableInTouchMode(true);
        imgHemo.requestFocus();


        updatePresenter = new UpdatePresenter(this);
        UpdateVersionBean updateVersionBean = new UpdateVersionBean();
        updatePresenter.Update(updateVersionBean);

    }

    /**
     * 获取网络回复的广播
     *
     * @return
     */
    BroadcastReceiver netBroadcastReceiver= new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals("connect_recover")&&intent.getIntExtra("recover",0)==400){
                presenter.onHomeLunbo("20", IsStringSPUtils.IsUid(),IsStringSPUtils.getSid());
            }
        }
    };
    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(netBroadcastReceiver);
    }
    /**
     * 获取滚动的高度
     *
     * @return
     */
    private int getScroll() {
        View v = myListView.getChildAt(0);//获取listVIew的第一个子View
        if (v instanceof ImageView) {//如果是继承自ImageView
            if (v != null) {
                int top = v.getTop();//获取图片顶部的坐标
                return -top;//这里作为我们滚动的值返回
            } else {
                return 0;
            }
        } else {//如果不是继承自ImageView，说明已经把headerView完全滚出了屏幕,这里减去了标题栏的高度
            return cCarouselView.getHeight() - (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 70, getResources().getDisplayMetrics());
        }
    }

    /**
     * 根据滚动的高度，改变标题栏透明度
     *
     * @param scroll
     */
    private void changeTitle(int scroll) {
        int height = cCarouselView.getHeight() - (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 70, getResources().getDisplayMetrics());
        float alpha = 1f / height;
        float a = alpha * scroll;//这里范围从0~1，0完全透明，1不透明
        a = a * 255;//这里转换成背景透明度的值0~255
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imgHemo:
                presenter.onHomeLunbo("10", IsStringSPUtils.IsUid(),IsStringSPUtils.getSid());
                showProgressDialog("数据加载中...", true);
                break;
            case R.id.mTextview:
                if (id != null || !id.equals("")) {
                    Intent intent = new Intent(getActivity(), WebActivity.class);
                    intent.putExtra("title", homebean != null ? homebean.getNotice().get(0).getPost_title() : "新闻详情");
                    intent.putExtra("url", Const.WEB + "web/news/id/" + id);
                    startActivity(intent);
                }
                break;
        }

    }


    @Override
    public void update(Observable o, Object arg) {
        ResultEntity entity = handlerError(arg);
        if (entity != null) {
            if (entity.getCode().equals("1111")) {
                Intent intent = new Intent(MyApplication.instance, LoginActivity.class);
                startActivity(intent);
                return;
            }
            if (entity.getMsg().equals("数据解析有误")) {
                closeProgressDialog();
            }
            if (entity.getEventType() == UpdatePresenter.update_success) {
                UpdateVersionBean appUpdateBean = (UpdateVersionBean) entity.getData();
                String jgVersion = appUpdateBean.getAndroid_version();
                int versionInt=0;
                if (!jgVersion.equals("")){
                    versionInt = Integer.parseInt(jgVersion.replace(".", ""));
                }
                String oldVersion =getAppVersionName(getActivity());
                int versionoldInt = Integer.parseInt(oldVersion.replace(".", ""));
                if (versionoldInt <versionInt){
                    onManager(appUpdateBean);
                }else{
                }
            } else if (entity.getEventType() == UpdatePresenter.update_fail) {
                MAlert.alert("更新解析失败");
            }
            if (entity.getEventType() == presenter.Home_success) {
                try {
                    homebean = (Homebean) entity.getData();
                    linHome.setBackgroundResource(R.color.gray_divider);
                    linteMessge.setVisibility(View.VISIBLE);//公告和消息，但数据出来才他们显示，
                    relyoutGongao.setVisibility(View.VISIBLE);
                    Log.d("Lunbos", homebean.getBanner().get(0).getImg() + "");
                    if (homebean.getNotice() != null && homebean.getNotice().size() != 0) {
                        mTextview.setText(homebean.getNotice().get(0).getPost_title());
                        mTextview.setMovementMethod(ScrollingMovementMethod.getInstance());
                        //  tvweiceshi.setText(homebean.getNotice().get(0).getPost_excerpt());
                        tvweiceshi.setText("微测试");
                        id = homebean.getNotice().get(0).getId();
                    } else {
                        tvweiceshi.setText("微测试");
                    }

                    adapter = new HomeAdapter(getActivity(), homebean);
                    XImageLoader.load(Const.IMAGE_HEAD + homebean.getBanner().get(0).getImg(), imgHemo);
                    myListView.setAdapter(adapter);
                    adapter.notifyDataSetChanged();
                    closeProgressDialog();
                } catch (Exception e) {

                }
            }

        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {// 根据反馈值判断当前网络状态
            case 1:
                String keyStr = data.getStringExtra("key");
                System.out.println("--------- onActivityResult -------keyStr="
                        + keyStr);
                if ("-1".equals(keyStr)) {
                    MAlert.alert("网络不可用");
//                    showTips(R.drawable.tips_error, "网络不可用...");
//                    text_type.setText("当前网络不可用");
                } else {
                    MAlert.alert("网络恢复正常");
                    getActivity().sendBroadcast(new Intent("connect_recover").putExtra("recover",400));
//                    showTips(R.drawable.tips_smile, "网络已恢复正常...");
                    if ("1".equals(keyStr)) {
//                        text_type.setText("当前连接网络为WiFi");
                    } else if ("2".equals(keyStr)) {
//                        text_type.setText("当前连接网络为wap网络");
                    } else if ("3".equals(keyStr)) {
//                        text_type.setText("当前连接网络为net网络");
                    }
                }
                break;
        }
    }

    public void onManager(UpdateVersionBean appUpdateBean) {
        UpdateManager manager = new UpdateManager(getActivity(),
                appUpdateBean.getAndroid_update_log()+ "",
                appUpdateBean.getAndroid_version_url(),appUpdateBean.getAndroid_version());
        manager.checkUpdateInfo();
    }
}
